<template>
  <!-- <div style="width:100%;heihgt:100%" ref="rootmap" class="web-map">
    <slot/>
  </div> -->
  <div id="map" ref="rootmap">
  </div>
</template>
 
<script>
import $ from "jquery";
import "ol/ol.css"
import { Map, View } from "ol"
import ol from "openlayers"
import mapConfig from './config/mapConfig'
import layerCreator from "@/components/map/olLib/layerCreator"
import mapHelper from "@/components/map/olLib/mapHelper"

console.log('mapConfig', mapConfig)
console.log('layerCreator', layerCreator)
// let coor = ol.proj.transform([113.436, 27.305], 'EPSG:4326', 'EPSG:3857');
export default {
  name: 'WebMap',
  props: ['target'],
  data() {
    return {
      map: null
    };
  },
  mounted() {
    var mapcontainer = this.$refs.rootmap;
    this.$nextTick(function () {
      let map = new Map({
      // let map = new ol.Map({
        // target: 'indexContent',
        target: mapcontainer,
        // controls: [],
        layers: mapConfig.mapCfg.streetmap(),
        // interactions: ol.interaction.defaults(mapConfig.mapInteractionCfg),
        view: new View({
        // view: new ol.View({
          projection: "EPSG:4326",    //使用这个坐标系
          // projection: "EPSG:3857",    //使用这个坐标系
          center: mapConfig.mapCfg.center, 
          // center: coor,
          zoom: mapConfig.mapCfg.zoom,
          // maxZoom: 14,
          // minZoom: 7.2,
        })
      });
      // console.log('mapcontainer', mapcontainer)
      console.log('11111111', map)

      //初始化图层组
      let layers = mapConfig.layers;
      console.log('layers', layers)
      for (var i = 0, len = layers.length - 1; len >= 0; len--) {
        var group = layerCreator.createGroup(layers[len]);
        if (group) {
          // map.addLayer(group);
        }
        // console.log('group', group)
      }
      console.log('--------', map)

      this.GLOBAL.currentMapObj = map; //全局属性初始化
      this.map = map;
      this.GLOBAL.mapUtil = new mapHelper(map);
      let thisVue = this;
      // window.thatVue = this;

      map.on("click", function (evt) { //地图点击事件
        console.log('map click', evt)
        if (evt.dragging) {
          return
        }
        var coordinate = evt.coordinate
        var t = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326')
        console.log('coordinate', coordinate)
        console.log('transform coordinate', t)

        if (thisVue.displayFeatureInfo(coordinate)) {
          return;
        }
      });

      map.on("pointermove", function (evt) { //鼠标移动
        // console.log('pointermove', evt)
        map.getTargetElement().style.cursor = "";
        var coordinate = evt.coordinate;
        if (thisVue.FeatureOverInfo(coordinate, evt.pixel)) {
          return;
        }
      });

      map.on("moveend", function (e) {
        var zoom = map.getView().getZoom();  //获取当前地图的缩放级别
        console.log('moveend', zoom, e);

      });
      
    })
  },

  methods: {
    //地图图标点击事件
    displayFeatureInfo(coordinate) {
      console.log('displayFeatureInfo', coordinate)
      if ($("#popup").length > 0) {
        $("#popup").remove();
      }
      let pixel = this.GLOBAL.currentMapObj.getPixelFromCoordinate(coordinate);
      let features = {length: 0};
      let that = this;

      let clickLayers = mapConfig.clickLayers;

      this.GLOBAL.currentMapObj.forEachFeatureAtPixel(pixel, function (feature, layer) {
        features.length = features.length + 1;
        let title = layer.get("title");

        let obj = features[title];
        if (!obj) {
          obj = [];
        }
        obj.push(feature);
        features[title] = obj;


      });

      for (let i = 0; i < clickLayers.length; i++) {
        let obj = features[clickLayers[i].layerName];
        if (obj && obj.length > 0) {
          let code = obj[0].get(clickLayers[i].feildName) || "";
          let title = obj[0].get(clickLayers[i].titleField) || "";
          let sttp = obj[0].get(clickLayers[i].sttp) || ''
          let pointType = 0;

          if (code == "") {

            //alert(clickLayers[i].layerName + clickLayers[i].feildName + '属性不存在！');
            continue;
          } else {

            if (clickLayers[i].isOne) {

              /* pointType：1：雨量站 ，2：河道站 ，3：水库站 ，4:河道雨量一体站 5:水库雨量一体站
                  根据标注进行判断
                */
              pointType = clickLayers[i].type;
              for (let j = 0; j < clickLayers[i].onePre.length; j++) {
                // if (
                //   $("#" + clickLayers[i].onePre[j].content + code).length > 0
                // ) {
                pointType = clickLayers[i].onePre[j].type;
                break;
                // }
              }
            }
            let paramsJSON = JSON.stringify({
              id: code,
              name: title,
              layer:
                clickLayers[i].cLayerName != undefined ? clickLayers[i].cLayerName : clickLayers[i].layerName,
              pointType: pointType
            }); // id:主键   name:窗口标题
            let flagWaring = true;
            for (var i = 0; i < $(".ol-selectable").length; i++) {
              $(".ol-selectable").eq(i).show();
            }
            let tempHtml = "";
            let options = {};
            // //console.log('pointType', pointType)
            switch (pointType) {
              case 1://水文站
                tempHtml = '<swzWin :code="data"></swzWin>';
                break;
              case 7:
                if (sttp == 'RR') {
                  tempHtml = '<skWindow :code="data"></skWindow>';
                } else if (sttp == "Z" || sttp == "Z") {
                  tempHtml = '<riverWin :code="data"></riverWin>';
                } else if (sttp == "SS") {
                  tempHtml = '<soilWindow :code="data"></soilWindow>';
                } else if (sttp == "PP") {
                  tempHtml = '<rainWin :code="data"></rainWin>';
                }
                break;
            }
            options = {width: 500};
            options.title = title;
            options.content = tempHtml;
            if (flagWaring) {
              this.GLOBAL.mapUtil.popup(coordinate, options, obj[0].getProperties());
            }
            return true;
          }
          return;
        }
      }
    },

    //鼠标样式
    FeatureOverInfo(coordinate, pix) {
      let pixel = this.GLOBAL.currentMapObj.getPixelFromCoordinate(coordinate);
      let features = {length: 0};
      this.GLOBAL.currentMapObj.forEachFeatureAtPixel(pixel, function (feature, layer) {
        features.length = features.length + 1;
        let title = layer.get("title");
        let obj = features[title];
        if (!obj) {
          obj = [];
        }
        obj.push(feature);
        features[title] = obj;
      });
      for (let i = 0; i < mapConfig.clickLayers.length; i++) {
        let obj = features[mapConfig.clickLayers[i].layerName];
        // console.log('clickLayers', obj)
        if (obj && obj.length > 0) {
          console.log('==========')
          this.GLOBAL.currentMapObj.getTargetElement().style.cursor = this.GLOBAL.currentMapObj.hasFeatureAtPixel(pix) ? "pointer" : "";
          if (obj[0].get('BJJ')) {
            let Marker = new ol.Feature({
              id: "N" + obj[0].get('STCD'),
              type: "warnMarker",
              geometry: new ol.geom.Point(
                ol.proj.transform(
                  [parseFloat(obj[0].get('LGTD')), parseFloat(obj[0].get('LTTD'))],
                  "EPSG:4326",
                  "EPSG:3857"
                )
              )
            });
            let a = obj[0].get('WRZ')
            if (a == null) {
              a = " - "
            }
            let n = obj[0].get('STNM') + ': 水位:' + obj[0].get('Z') + " | 警戒值:" + a
            let stylesWarnP = new ol.style.Style({
              text: new ol.style.Text({
                text: n,
                fill: new ol.style.Fill({
                  color: '#fff'
                }),
                backgroundFill: new ol.style.Fill({
                  color: '#4287b3',
                }),
                padding: [2, 2, 2, 2],
                offsetY: -20
              }),
              zindex: 500,
            });
            Marker.setStyle(stylesWarnP);
            window.thatVue.GLOBAL.mapUtil
              .getLayer('河道站描述')
              .getSource()
              .addFeature(Marker);
          }
          if (obj[0].get('BXX')) {
            let Marker = new ol.Feature({
              id: "N" + obj[0].get('STCD'),
              type: "warnMarker",
              geometry: new ol.geom.Point(
                ol.proj.transform(
                  [parseFloat(obj[0].get('LGTD')), parseFloat(obj[0].get('LTTD'))],
                  "EPSG:4326",
                  "EPSG:3857"
                )
              )
            });
            let a = obj[0].get('W')
            if (a == null) {
              a = " - "
            }
            let n = obj[0].get('STNM') + ': 库上水位:' + obj[0].get('RZ') + " | 蓄水量:" + a;
            let stylesWarnP = new ol.style.Style({
              text: new ol.style.Text({
                text: n,
                fill: new ol.style.Fill({
                  color: '#fff'
                }),
                backgroundFill: new ol.style.Fill({
                  color: '#4287b3',
                }),
                padding: [2, 2, 2, 2],
                offsetY: -20
              }),
              zindex: 500,
            });
            Marker.setStyle(stylesWarnP);
            window.thatVue.GLOBAL.mapUtil
              .getLayer('水库站描述')
              .getSource()
              .addFeature(Marker);
          }
          if (obj[0].get('TYPE') == 'SS') {
            let Marker = new ol.Feature({
              id: "N" + obj[0].get('STCD'),
              type: "warnMarker",
              geometry: new ol.geom.Point(
                ol.proj.transform(
                  [parseFloat(obj[0].get('LGTD')), parseFloat(obj[0].get('LTTD'))],
                  "EPSG:4326",
                  "EPSG:3857"
                )
              )
            });
            let XDSD;
            if (obj[0].get('XDSD')) {
              XDSD = obj[0].get('XDSD') + '%';
            } else {
              XDSD = '-';
            }
            let n = obj[0].get('STNM') + ': 相对湿度:' + XDSD;
            let stylesWarnP = new ol.style.Style({
              text: new ol.style.Text({
                text: n,
                fill: new ol.style.Fill({
                  color: '#fff'
                }),
                backgroundFill: new ol.style.Fill({
                  color: '#4287b3',
                }),
                padding: [2, 2, 2, 2],
                offsetY: -20
              }),
              zindex: 500,
            });
            Marker.setStyle(stylesWarnP);
            window.thatVue.GLOBAL.mapUtil
              .getLayer('墒情站描述')
              .getSource()
              .addFeature(Marker);
          }

        }
      }
    },

    async doCityCenter(cityInfo, zoom) {
      console.log('doCityCenter', cityInfo)
      // let that = this;
      // console.log('ssssssss',that.map)
      // this.map.setView(new ol.View({
      //   center: ol.proj.transform([cityInfo[0], cityInfo[1]], 'EPSG:4326', 'EPSG:3857'),
      //   zoom: 9.0,
      //   maxZoom: 14,//最大等级
      //   minZoom: 7.0,//最小等级
      // }));

      this.map.setView(new View({
        center: ol.proj.transform([cityInfo[0], cityInfo[1]], 'EPSG:4326', 'EPSG:3857'),
        zoom: zoom,
        // maxZoom: 14,//最大等级
        // minZoom: 7.0,//最小等级
      }));

    }

  }

};
</script>
 
<style>
#map{height:100%;}
/*隐藏ol的一些自带元素*/
/* .ol-attribution,.ol-zoom { display: none;} */
 
</style>